﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;

namespace TestApp
{
	public class QueryManager : INotifyPropertyChanged
	{
		public DataTable Data { get; set; }
		public string Query { get; set; }
		public bool Success { get; set; }
		public string Error { get; set; }
		public List<SyntaxTree> Syntax { get; set; }
		public string ConnectionString { get; set; }

		public QueryManager()
		{
			Query = "select * from DocLog" + Environment.NewLine + "where id = 69";
			ConnectionString = "Data Source=(local);Initial Catalog=*;Integrated Security=True;Connection Timeout=9999";
		}

		public void Run ()
		{
			try
			{
				Data = new DataTable ();
				using ( SqlConnection myConnection = new SqlConnection ( ConnectionString ) )
				{
					myConnection.Open ();
					using ( SqlCommand myCommand = new SqlCommand ( Query, myConnection ) )
					{
						using ( SqlDataReader reader = myCommand.ExecuteReader () )
						{
							Data.Load ( reader );
							PropertyChanged ( this, new PropertyChangedEventArgs ( "Data" ) );
						}
					}
				}

				this.Syntax = new List<SyntaxTree> { new SyntaxTree ("Query", SQLParser.parseText ( Query ) ) };

				Success = true;
				PropertyChanged ( this, new PropertyChangedEventArgs ( "Success" ) );
				PropertyChanged ( this, new PropertyChangedEventArgs ( "Syntax" ) );
			}
			catch ( Exception ex )
			{
				Success = false;
				Error = ex.Message;
				PropertyChanged ( this, new PropertyChangedEventArgs ( "Success" ) );
				PropertyChanged ( this, new PropertyChangedEventArgs ( "Error" ) );
			}
		}

		#region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged = delegate { };

		#endregion
	}
}
